<template>
  <ContentWrap>
    <!-- 搜索工作栏 -->
    <el-form
      class="-mb-15px"
      :model="queryParams"
      ref="queryFormRef"
      :inline="true"
      label-width="120px"
    >
      <el-form-item label="平台编号" prop="platformId">
        <el-input
          v-model="queryParams.platformId"
          placeholder="请输入平台编号"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="店铺编号" prop="storeId">
        <el-input
          v-model="queryParams.storeId"
          placeholder="请输入店铺编号（为空表示平台级配置）"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="费率类型" prop="feeType">
        <el-select
          v-model="queryParams.feeType"
          placeholder="请选择费率类型"
          clearable
          class="!w-240px"
        >
          <el-option
            v-for="dict in getStrDictOptions(DICT_TYPE.CROSSBORDER_DATA_TYPE)"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="费率名称" prop="feeName">
        <el-input
          v-model="queryParams.feeName"
          placeholder="请输入费率名称"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="英文名称" prop="feeNameEn">
        <el-input
          v-model="queryParams.feeNameEn"
          placeholder="请输入英文名称"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="计算方式" prop="calculationMethod">
        <el-select
          v-model="queryParams.calculationMethod"
          placeholder="请选择计算方式"
          clearable
          class="!w-240px"
        >
          <el-option
            v-for="dict in getIntDictOptions(DICT_TYPE.CROSSBORDER_CALCULATION_METHOD)"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="费率（百分比时为小数）" prop="feeRate" label-width="180px">
        <el-input
          v-model="queryParams.feeRate"
          placeholder="请输入费率（百分比时为小数，如0.15表示15%）"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="固定金额" prop="fixedAmount">
        <el-input
          v-model="queryParams.fixedAmount"
          placeholder="请输入固定金额"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="最小费用" prop="minFee">
        <el-input
          v-model="queryParams.minFee"
          placeholder="请输入最小费用"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="最大费用" prop="maxFee">
        <el-input
          v-model="queryParams.maxFee"
          placeholder="请输入最大费用"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="货币代码" prop="currency">
        <el-input
          v-model="queryParams.currency"
          placeholder="请输入货币代码"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="适用分类ID" prop="categoryIds">
        <el-input
          v-model="queryParams.categoryIds"
          placeholder="请输入适用分类ID，逗号分隔"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="适用产品类型" prop="productTypes">
        <el-input
          v-model="queryParams.productTypes"
          placeholder="请输入适用产品类型，逗号分隔"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="阶梯费率配置" prop="tierConfig">
        <el-input
          v-model="queryParams.tierConfig"
          placeholder="请输入阶梯费率配置JSON"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="生效日期" prop="effectiveDate">
        <el-date-picker
          v-model="queryParams.effectiveDate"
          value-format="YYYY-MM-DD HH:mm:ss"
          type="daterange"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          :default-time="[new Date('1 00:00:00'), new Date('1 23:59:59')]"
          class="!w-220px"
        />
      </el-form-item>
      <el-form-item label="失效日期" prop="expireDate">
        <el-date-picker
          v-model="queryParams.expireDate"
          value-format="YYYY-MM-DD HH:mm:ss"
          type="daterange"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          :default-time="[new Date('1 00:00:00'), new Date('1 23:59:59')]"
          class="!w-220px"
        />
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select
          v-model="queryParams.status"
          placeholder="请选择状态"
          clearable
          class="!w-240px"
        >
          <el-option
            v-for="dict in getIntDictOptions(DICT_TYPE.CROSSBORDER_COMMON_STATUS)"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="备注" prop="remark">
        <el-input
          v-model="queryParams.remark"
          placeholder="请输入备注"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="创建时间" prop="createTime">
        <el-date-picker
          v-model="queryParams.createTime"
          value-format="YYYY-MM-DD HH:mm:ss"
          type="daterange"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          :default-time="[new Date('1 00:00:00'), new Date('1 23:59:59')]"
          class="!w-220px"
        />
      </el-form-item>
      <el-form-item>
        <el-button @click="handleQuery"><Icon icon="ep:search" class="mr-5px" /> 搜索</el-button>
        <el-button @click="resetQuery"><Icon icon="ep:refresh" class="mr-5px" /> 重置</el-button>
        <el-button
          type="primary"
          plain
          @click="openForm('create')"
          v-hasPermi="['crossborder:platform-fee-config:create']"
        >
          <Icon icon="ep:plus" class="mr-5px" /> 新增
        </el-button>
        <el-button
          type="success"
          plain
          @click="handleExport"
          :loading="exportLoading"
          v-hasPermi="['crossborder:platform-fee-config:export']"
        >
          <Icon icon="ep:download" class="mr-5px" /> 导出
        </el-button>
        <el-button
            type="danger"
            plain
            :disabled="isEmpty(checkedIds)"
            @click="handleDeleteBatch"
            v-hasPermi="['crossborder:platform-fee-config:delete']"
        >
          <Icon icon="ep:delete" class="mr-5px" /> 批量删除
        </el-button>
      </el-form-item>
    </el-form>
  </ContentWrap>

  <!-- 列表 -->
  <ContentWrap>
    <el-table
        row-key="id"
        v-loading="loading"
        :data="list"
        :stripe="true"
        :show-overflow-tooltip="true"
        @selection-change="handleRowCheckboxChange"
    >
    <el-table-column type="selection" width="55" />
      <el-table-column label="费率配置编号" align="center" prop="id" />
      <el-table-column label="平台编号" align="center" prop="platformId" />
      <el-table-column label="店铺编号" align="center" prop="storeId" width="120" />
      <el-table-column label="费率类型" align="center" prop="feeType" width="120">
        <template #default="scope">
          <dict-tag :type="DICT_TYPE.CROSSBORDER_DATA_TYPE" :value="scope.row.feeType" />
        </template>
      </el-table-column>
      <el-table-column label="费率名称" align="center" prop="feeName" />
      <el-table-column label="英文名称" align="center" prop="feeNameEn" />
      <el-table-column label="计算方式" align="center" prop="calculationMethod" width="120">
        <template #default="scope">
          <dict-tag :type="DICT_TYPE.CROSSBORDER_CALCULATION_METHOD" :value="scope.row.calculationMethod" />
        </template>
      </el-table-column>
      <el-table-column label="费率" align="center" prop="feeRate" />
      <el-table-column label="固定金额" align="center" prop="fixedAmount" />
      <el-table-column label="最小费用" align="center" prop="minFee" />
      <el-table-column label="最大费用" align="center" prop="maxFee" />
      <el-table-column label="货币代码" align="center" prop="currency" />
      <el-table-column label="适用分类ID" align="center" prop="categoryIds" />
      <el-table-column label="适用产品类型" align="center" prop="productTypes" />
      <el-table-column label="阶梯费率配置JSON" align="center" prop="tierConfig" />
      <el-table-column label="生效日期" align="center" prop="effectiveDate" />
      <el-table-column label="失效日期" align="center" prop="expireDate" />
      <el-table-column label="状态" align="center" prop="status" width="100">
        <template #default="scope">
          <dict-tag :type="DICT_TYPE.CROSSBORDER_COMMON_STATUS" :value="scope.row.status" />
        </template>
      </el-table-column>
      <el-table-column label="备注" align="center" prop="remark" />
      <el-table-column
        label="创建时间"
        align="center"
        prop="createTime"
        :formatter="dateFormatter"
        width="180px"
      />
      <el-table-column label="操作" align="center" min-width="120px">
        <template #default="scope">
          <el-button
            link
            type="primary"
            @click="openForm('update', scope.row.id)"
            v-hasPermi="['crossborder:platform-fee-config:update']"
          >
            编辑
          </el-button>
          <el-button
            link
            type="danger"
            @click="handleDelete(scope.row.id)"
            v-hasPermi="['crossborder:platform-fee-config:delete']"
          >
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <Pagination
      :total="total"
      v-model:page="queryParams.pageNo"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />
  </ContentWrap>

  <!-- 表单弹窗：添加/修改 -->
  <PlatformFeeConfigForm ref="formRef" @success="getList" />
</template>

<script setup lang="ts">
import { isEmpty } from '@/utils/is'
import { dateFormatter } from '@/utils/formatTime'
import download from '@/utils/download'
import { DICT_TYPE, getIntDictOptions, getStrDictOptions, getBoolDictOptions } from '@/utils/dict'
import { PlatformFeeConfigApi, PlatformFeeConfigVO } from '@/api/crossborder/platformfeeconfig'
import PlatformFeeConfigForm from './PlatformFeeConfigForm.vue'

/** 跨境电商平台费率配置 列表 */
defineOptions({ name: 'PlatformFeeConfig' })

const message = useMessage() // 消息弹窗
const { t } = useI18n() // 国际化

const loading = ref(true) // 列表的加载中
const list = ref<PlatformFeeConfigVO[]>([]) // 列表的数据
const total = ref(0) // 列表的总页数
const queryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  platformId: undefined,
  storeId: undefined,
  feeType: undefined,
  feeName: undefined,
  feeNameEn: undefined,
  calculationMethod: undefined,
  feeRate: undefined,
  fixedAmount: undefined,
  minFee: undefined,
  maxFee: undefined,
  currency: undefined,
  categoryIds: undefined,
  productTypes: undefined,
  tierConfig: undefined,
  effectiveDate: [],
  expireDate: [],
  status: undefined,
  remark: undefined,
  createTime: [],
})
const queryFormRef = ref() // 搜索的表单
const exportLoading = ref(false) // 导出的加载中

/** 查询列表 */
const getList = async () => {
  loading.value = true
  try {
    const data = await PlatformFeeConfigApi.getPlatformFeeConfigPage(queryParams)
    list.value = data.list
    total.value = data.total
  } finally {
    loading.value = false
  }
}

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.pageNo = 1
  getList()
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value.resetFields()
  handleQuery()
}

/** 添加/修改操作 */
const formRef = ref()
const openForm = (type: string, id?: number) => {
  formRef.value.open(type, id)
}

/** 删除按钮操作 */
const handleDelete = async (id: number) => {
  try {
    // 删除的二次确认
    await message.delConfirm()
    // 发起删除
    await PlatformFeeConfigApi.deletePlatformFeeConfig(id)
    message.success(t('common.delSuccess'))
    // 刷新列表
    await getList()
  } catch {}
}

/** 批量删除跨境电商平台费率配置 */
const handleDeleteBatch = async () => {
  try {
    // 删除的二次确认
    await message.delConfirm()
    await PlatformFeeConfigApi.deletePlatformFeeConfigList(checkedIds.value);
    message.success(t('common.delSuccess'))
    await getList();
  } catch {}
}

const checkedIds = ref<number[]>([])
const handleRowCheckboxChange = (records: PlatformFeeConfigVO[]) => {
  checkedIds.value = records.map((item) => item.id);
}

/** 导出按钮操作 */
const handleExport = async () => {
  try {
    // 导出的二次确认
    await message.exportConfirm()
    // 发起导出
    exportLoading.value = true
    const data = await PlatformFeeConfigApi.exportPlatformFeeConfig(queryParams)
    download.excel(data, '跨境电商平台费率配置.xls')
  } catch {
  } finally {
    exportLoading.value = false
  }
}

/** 初始化 **/
onMounted(() => {
  getList()
})
</script>